********************************************************************************
* Replication file for Cui (2020 JEEM)
* "Climate change and adaptation in agriculture: Evidence from US cropping patterns"
*
* Step 1.1: Convert county-level daily weather data to annual weather variables
********************************************************************************


* set path
	
	global family "..."
	global data  ".../dta"


* load county-level daily weather

	use $data/DailyTPByYearandFips_cropAreaWeighted.dta, clear
		
* define GS (Apr-Sep)

	gen month = month(dateNum)
	keep if month>3 & month<10

* define degree day variables (within-day interpolated)

	foreach b in 10 29 30 {
		qui gen dday`b'C = 0
		qui replace dday`b'C = tAvg - `b' if (`b' <= tMin)

		qui gen tempSave = acos( (2*`b'-tMax-tMin)/(tMax-tMin) )
		qui replace dday`b'C = ( (tAvg-`b')*tempSave + (tMax-tMin)*sin(tempSave)/2 )/_pi ///
			if ( (tMin < `b') & (`b' < tMax) )
		drop tempSave
		}
		
* define daily tAvg bins (# of days)
	
	forvalues t = 8(3)32 {
		gen dbin`t' = (tAvg>=`t'-3 & tAvg<`t')
		}
	gen dbin32plus = (tAvg>=32)
		
* aggregate daily to annual
	
	collapse tAvg (sum) dday* prec dbin*, by(fips year)

* generate variables	
	
	gen gdd29 = dday10C - dday29C
	gen gdd30 = dday10C - dday30C
	rename dday29C hdd29
	rename dday30C hdd30
	sum gdd* hdd* dbin*
	
	xtset fips year
	gen lag_tAvg = L.tAvg
	gen lag_prec = L.prec
	
	* save
	save $data/prism_aw_county_apr_sep.dta, replace
